package com.brainwave.bluetooth;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

import com.brainwave.MainActivity;
import com.brainwave.R;
import com.brainwave.utils.Constants;
import com.brainwave.utils.Logger;

/**
 * 蓝牙服务类
 * 作为前台服务运行，管理蓝牙连接和数据处理
 */
public class BluetoothService extends Service implements 
        BluetoothManager.BluetoothConnectionListener,
        NeuroSkyProtocol.NeuroSkyDataListener {
    
    private static final String TAG = "BluetoothService";
    private static final int NOTIFICATION_ID = 1001;
    
    // 服务绑定器
    private final IBinder binder = new BluetoothServiceBinder();
    
    // 蓝牙管理器和协议解析器
    private BluetoothManager bluetoothManager;
    private NeuroSkyProtocol neuroSkyProtocol;
    
    // 服务监听器
    private BluetoothServiceListener serviceListener;
    
    /**
     * 服务监听器接口
     */
    public interface BluetoothServiceListener {
        void onConnectionStateChanged(BluetoothManager.ConnectionState state);
        void onDeviceFound(BluetoothDevice device);
        void onPoorSignalReceived(int poorSignal);
        void onAttentionReceived(int attention);
        void onMeditationReceived(int meditation);
        void onBlinkReceived(int blinkStrength);
        void onRawDataReceived(int rawValue);
        void onEegPowerReceived(NeuroSkyProtocol.EegPowerData eegPower);
        void onError(String error);
    }
    
    /**
     * 服务绑定器
     */
    public class BluetoothServiceBinder extends Binder {
        public BluetoothService getService() {
            return BluetoothService.this;
        }
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        // 初始化蓝牙管理器
        bluetoothManager = new BluetoothManager(this);
        bluetoothManager.addConnectionListener(this);
        
        // 初始化协议解析器
        neuroSkyProtocol = new NeuroSkyProtocol();
        neuroSkyProtocol.addDataListener(this);
        
        // 创建通知渠道
        createNotificationChannel();
        
        Logger.d(TAG, "BluetoothService created");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification());
        
        Logger.d(TAG, "BluetoothService started");
        return START_STICKY; // 服务被杀死后自动重启
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        
        if (bluetoothManager != null) {
            bluetoothManager.destroy();
        }
        
        if (neuroSkyProtocol != null) {
            neuroSkyProtocol.destroy();
        }
        
        Logger.d(TAG, "BluetoothService destroyed");
    }
    
    /**
     * 设置服务监听器
     */
    public void setServiceListener(BluetoothServiceListener listener) {
        this.serviceListener = listener;
    }
    
    /**
     * 获取蓝牙管理器
     */
    public BluetoothManager getBluetoothManager() {
        return bluetoothManager;
    }
    
    /**
     * 开始搜索设备
     */
    public boolean startDiscovery() {
        if (bluetoothManager != null) {
            return bluetoothManager.startDiscovery();
        }
        return false;
    }
    
    /**
     * 停止搜索设备
     */
    public void stopDiscovery() {
        if (bluetoothManager != null) {
            bluetoothManager.stopDiscovery();
        }
    }
    
    /**
     * 连接到设备
     */
    public void connectToDevice(BluetoothDevice device) {
        if (bluetoothManager != null) {
            bluetoothManager.connectToDevice(device);
        }
    }
    
    /**
     * 断开连接
     */
    public void disconnect() {
        if (bluetoothManager != null) {
            bluetoothManager.disconnect();
        }
    }
    
    /**
     * 获取连接状态
     */
    public BluetoothManager.ConnectionState getConnectionState() {
        if (bluetoothManager != null) {
            return bluetoothManager.getConnectionState();
        }
        return BluetoothManager.ConnectionState.DISCONNECTED;
    }
    
    /**
     * 获取已连接的设备
     */
    public BluetoothDevice getConnectedDevice() {
        if (bluetoothManager != null) {
            return bluetoothManager.getConnectedDevice();
        }
        return null;
    }
    
    /**
     * 创建通知渠道
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    Constants.NOTIFICATION_CHANNEL_ID,
                    Constants.NOTIFICATION_CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription(Constants.NOTIFICATION_CHANNEL_DESCRIPTION);
            channel.setShowBadge(false);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
    
    /**
     * 创建通知
     */
    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, 
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? 
                        PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_UPDATE_CURRENT
        );
        
        String contentText = getString(R.string.notification_content_disconnected);
        int iconRes = R.drawable.ic_bluetooth_disabled;
        
        if (bluetoothManager != null) {
            BluetoothManager.ConnectionState state = bluetoothManager.getConnectionState();
            switch (state) {
                case CONNECTED:
                    BluetoothDevice device = bluetoothManager.getConnectedDevice();
                    contentText = getString(R.string.notification_content_connected, 
                            device != null ? device.getName() : "Unknown");
                    iconRes = R.drawable.ic_bluetooth_connected;
                    break;
                case CONNECTING:
                    contentText = getString(R.string.notification_content_connecting);
                    break;
                case ERROR:
                    contentText = getString(R.string.notification_content_error);
                    break;
            }
        }
        
        return new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(contentText)
                .setSmallIcon(iconRes)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setShowWhen(false)
                .build();
    }
    
    /**
     * 更新通知
     */
    private void updateNotification() {
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        if (notificationManager != null) {
            notificationManager.notify(NOTIFICATION_ID, createNotification());
        }
    }
    
    // BluetoothManager.BluetoothConnectionListener 实现
    
    @Override
    public void onConnectionStateChanged(BluetoothManager.ConnectionState state) {
        updateNotification();
        
        if (serviceListener != null) {
            serviceListener.onConnectionStateChanged(state);
        }
        
        Logger.d(TAG, "Connection state changed: " + state);
    }
    
    @Override
    public void onDeviceFound(BluetoothDevice device) {
        if (serviceListener != null) {
            serviceListener.onDeviceFound(device);
        }
        
        Logger.d(TAG, "Device found: " + device.getName());
    }
    
    @Override
    public void onDataReceived(byte[] data) {
        // 将接收到的数据传递给协议解析器
        if (neuroSkyProtocol != null) {
            neuroSkyProtocol.parseData(data);
        }
    }
    
    @Override
    public void onError(String error) {
        if (serviceListener != null) {
            serviceListener.onError(error);
        }
        
        Logger.e(TAG, "Bluetooth error: " + error);
    }
    
    // NeuroSkyProtocol.NeuroSkyDataListener 实现
    
    @Override
    public void onPoorSignalReceived(int poorSignal) {
        if (serviceListener != null) {
            serviceListener.onPoorSignalReceived(poorSignal);
        }
    }
    
    @Override
    public void onAttentionReceived(int attention) {
        if (serviceListener != null) {
            serviceListener.onAttentionReceived(attention);
        }
    }
    
    @Override
    public void onMeditationReceived(int meditation) {
        if (serviceListener != null) {
            serviceListener.onMeditationReceived(meditation);
        }
    }
    
    @Override
    public void onBlinkReceived(int blinkStrength) {
        if (serviceListener != null) {
            serviceListener.onBlinkReceived(blinkStrength);
        }
    }
    
    @Override
    public void onRawDataReceived(int rawValue) {
        if (serviceListener != null) {
            serviceListener.onRawDataReceived(rawValue);
        }
    }
    
    @Override
    public void onEegPowerReceived(NeuroSkyProtocol.EegPowerData eegPower) {
        if (serviceListener != null) {
            serviceListener.onEegPowerReceived(eegPower);
        }
    }
    
    @Override
    public void onParseError(String error) {
        if (serviceListener != null) {
            serviceListener.onError("Parse error: " + error);
        }
    }
}